<?php

namespace app\controller\wmapi\partner;

use app\controller\wmapi\approvalsetting\ApproveSettingController;
use app\controller\wmapi\IndexController;
use app\model\WaChannel;
use app\model\WaSupplier;
use app\model\WaSupplierExamineApprove;
use app\model\WaSupplierExamineApproveFlow;
use Illuminate\Support\Facades;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\Admin;
use support\Request;
use app\model\WaAdmins;
use app\model\WaRoles;
use app\model\WaMembers;
use app\model\WaRules;
use app\model\WaDepartment;
use app\model\WaAdminRoles;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Cache;
use Tinywan\Validate\Validate;
use Intervention\Image\ImageManagerStatic as Image;

class SupplierController extends Validate
{
    /**
     * 供应商管理 -列表-分页
     * @param Request $request
     * @return mixed
     */
    public function supplierList(Request $request)
    {
        $param = $request->all();
        $fields = ['*'];
        $condition = [];
        $between = [];


        if ($param['name']) {
            $condition [] = ['name', 'like', '%' . $param['name'] . '%'];
        }

        if ($param['phone']) {
            $condition [] = ['phone', 'like', '%' . $param['phone'] . '%'];
        }


        if ($param['start_time'] && $param['end_time']) {
            $between [] = [$param['start_time'], $param['end_time']];
        }

        $condition [] = ['status', '!=', 4];

        $page = page($param['page']);
        $pageNum = pageNum($param['pageNum']);
        $rule = WaSupplier::list($page, $pageNum, $fields, $condition, $between);

        return IndexController::successed($rule, '供应商列表');
    }

    /**
     * 供应商管理 -列表-不分页
     * @param Request $request
     * @return mixed
     */
    public function supplierAll(Request $request)
    {
//        process($request);
        $param = $request->all();
        $fields = ['*'];
        $condition = [];
        if ($param['supplier_name']) {
            $condition [] = ['name', 'like', '%' . $param['supplier_name'] . '%']; // 供应商名称
        }

        $condition [] = ['status', '!=', 4];

        $rule = WaSupplier::all($fields, $condition);
        return IndexController::successed($rule, '供应商列表');
    }


    /**
     * 供应商-创建
     * @param Request $request
     * @return \support\Response
     */
    public function supplierCreate(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        /**
         * 验证规则
         */
        $data = [
            'name' => $param['name'], // 上牌供应商名字
            'credit_code' => $param['credit_code'],// 组织机构信用代码
            'linkman' => $param['linkman'], // 联系人
            'phone' => $param['phone'],
            'email' => $param['email'],
            'legal_person_name' => $param['legal_person_name'], // 法人姓名
            'legal_person_phone' => $param['legal_person_phone'], // 法人手机
            'legal_person_identity_card' => $param['legal_person_identity_card'], // 法人身份证号码
            'address' => $param['address'],
            'remark' => $param['remark'], // 备注
            'registered_address' => $param['registered_address'], // 注册地址
            'business_scope' => $param['business_scope'], // 经营范围

            'created_at' => dateTime(),
            'admin_id' => $adminId->id, // 创建人
            'status' => 0,

            'legal_person_identity_left' => $param['legal_person_identity_left'], // 法人身份证正面
            'door_imgs' => json_encode($param['door_imgs']), // 门店照片 多张 数组格式
            'legal_person_identity_right' => $param['legal_person_identity_right'], // 法人身份证反面
            'business_license_img' => $param['business_license_img'], // 营业执照号照片
            'main_brand' => $param['main_brand'], // 主营品牌
            'province' => $param['province'],
            'city' => $param['city'],
//            'subbranch_name' => $param['subbranch_name'],
//            'firmname' => $param['firmname'], // 企业名称


        ];
        if ($param['account_information']){
            $data['account_information'] =   json_encode($param['account_information']); // 账户信息
        }
//        $validate = self::validateAdd($data);
//        if (!$validate) {
//            return IndexController::errored('', '供应商入参有误');
//        }
        $where = [];
        $where [] = ['phone' ,'=', $param['phone']];
        $where [] = ['status' ,'!=', 4];
        $whereOr = [];
        $whereOr [] = ['name' ,'=', $param['name']];
        $whereOr [] = ['status' ,'!=', 4];
        $find = WaSupplier::findOr($where,$whereOr);
        $find = json_decode($find);
        if ($find) {
            if (property_exists($find, 'id')) {
                return IndexController::errored('', '供应商创建失败,供应商名称、电话已存在');
            }
        }
        \support\Db::beginTransaction();
        try {
            $supplier_id = WaSupplier::created($data);
            if (!$supplier_id) {
                return IndexController::errored($supplier_id, '供应商创建失败');
            }
            $sup_data = [
                'supplier_type' => 1, //  供应商类型： 1车辆供应商 2上牌供应商 3 国际货运代理 4保险供应商 5 国内物流
                'supplier_type_name' => '车辆供应商', //  供应商类型： 1车辆供应商 2上牌供应商 3 国际货运代理 4保险供应商 5 国内物流
                'service_type' => 1, //  服务类型： 1 车辆
                'service_type_name' => '车辆',
                'supplier_id' => $supplier_id,
                'supplier_name' => $param['name'],
            ];
//            $create_approve = SupplierController::commonCreateApprove($adminId,$sup_data);
//            if ($create_approve != 'true'){
//                return IndexController::errored($create_approve, '创建车辆供应商审批失败');
//            }

            \support\Db::commit();
            return IndexController::successed($supplier_id, '供应商创建成功');
        } catch (\Throwable $exception) {
            IndexController::logError('supplierCreate', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '供应商创建失败');
        }


    }

    public static function validateAdd($data)
    {
        $rule = [
            'name' => 'require', // 上牌供应商名字
            'address' => '',
            'phone' => 'require',
            'email' => 'require',
            'credit_code' => 'require',// 组织机构信用代码
            'linkman' => 'require', // 联系人
            'legal_person_name' => 'require', // 法人姓名
            'legal_person_phone' => 'require', // 法人手机
            'legal_person_identity_card' => 'require', // 法人身份证号码
            'registered_address' => '', // 注册地址
            'business_license_img' => '', // 营业执照号照片
//            'subbranch_name' => 'require', // 开户支行
            'business_scope' => '', // 经营范围
        ];


//        $validate = \Tinywan\Validate\Facade\Validate::rule($rule);
//
//        if (!$validate->check($data)) {
//            return $validate->getError();
//        }
        return true;
    }


    /**
     * 供应商-更新
     * @param Request $request
     * @return \support\Response
     */
    public function supplierEdit(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        /**
         * 验证规则
         */
        $data = [
            'name' => $param['name'], // 上牌供应商名字
            'credit_code' => $param['credit_code'],// 组织机构信用代码
            'linkman' => $param['linkman'], // 联系人
            'phone' => $param['phone'],
            'email' => $param['email'],
            'legal_person_name' => $param['legal_person_name'], // 法人姓名
            'legal_person_phone' => $param['legal_person_phone'], // 法人手机
            'legal_person_identity_card' => $param['legal_person_identity_card'], // 法人身份证号码
            'address' => $param['address'],
            'remark' => $param['remark'], // 备注
            'registered_address' => $param['registered_address'], // 注册地址
            'business_scope' => $param['business_scope'], // 经营范围
            'created_at' => dateTime(),
            'admin_id' => $adminId->id, // 创建人
            'status' => 0,

            'legal_person_identity_left' => $param['legal_person_identity_left'], // 法人身份证正面
            'door_imgs' => json_encode($param['door_imgs']), // 门店照片 多张 数组格式
            'legal_person_identity_right' => $param['legal_person_identity_right'], // 法人身份证反面
            'business_license_img' => $param['business_license_img'], // 营业执照号照片
            'main_brand' => $param['main_brand'], // 主营品牌
            'province' => $param['province'],
            'city' => $param['city'],
//            'subbranch_name' => $param['subbranch_name'],
//            'firmname' => $param['firmname'], // 企业名称

        ];
        if ($param['account_information']){
            $data['account_information'] =   json_encode($param['account_information']); // 账户信息
        }
//        $validate = self::validateAdd($data);
//        if (!$validate) {
//            return IndexController::errored('', '供应商入参有误');
//        }

        $where = [];
        $where [] = ['phone' ,'=', $param['phone']];
        $where [] = ['status' ,'!=', 4];
        $whereOr = [];
        $whereOr [] = ['name' ,'=', $param['name']];
        $whereOr [] = ['status' ,'!=', 4];
        $find = WaSupplier::findOr($where,$whereOr);
        $find = json_decode($find);
        if ($find){
            if (property_exists($find, 'id')) {
                if ($param['supplier_id'] != $find->id) {
                    return IndexController::errored('', '供应商更新失败,供应商电话已存在');
                }
            }
        }

        $condition = [];
        $condition [] = ['id', '=', intval($param['supplier_id'])];
        \support\Db::beginTransaction();
        try {
            $res = WaSupplier::updated($condition, $data);

            \support\Db::commit();
            return IndexController::successed($res, '供应商更新成功');
        } catch (\Throwable $exception) {
            IndexController::logError('supplierEdit', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '供应商更新失败');
        }

    }

    /**
     * 供应商-删除
     * @param Request $request
     * @return \support\Response
     */
    public function supplierDel(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $condition = [];
        $condition [] = ['id', '=', $param['supplier_id']];
//
        $data = [
            'status' => 4,
            'updated_at' => dateTime(),
        ];
        \support\Db::beginTransaction();
        try {
            $res = WaSupplier::updated($condition, $data);
            if(!$res){
                return IndexController::errored('', '供应商-删除失败');
            }
//            $del = WaSupplier::deleted(['id' => $param['supplier_id']]);
            \support\Db::commit();
            return IndexController::successed('', '供应商-删除成功');
        } catch (\Throwable $exception) {
            IndexController::logError('supplierDel', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '供应商-删除失败');
        }
    }
//
    /**
     * 供应商-详情
     * @param Request $request
     * @return \support\Response
     */
    public function supplierDetail(Request $request)
    {
//        process($request);
        $param = $request->all();

        $condition = [];
        $condition [] = ['id', '=', intval($param['supplier_id'])];

        $rule = WaSupplier::find($condition);
        return IndexController::successed($rule, '供应商信息');
    }


    /**
     * 通用创建供应商审批
     * @param $adminId
     * @param $supplier_type
     * @param $param
     */
    public static function commonCreateApprove($adminId,$sup_data){

        $supplier_type_name = '';
//        if ($sup_data['supplier_type'] == 1){
//            $supplier_type_name = '车辆供应商';
//        }elseif ($sup_data['supplier_type'] == 2){
//            $supplier_type_name = '上牌供应商';
//        }elseif ($sup_data['supplier_type'] == 3){
//            $supplier_type_name = '国际货运代理';
//        }elseif ($sup_data['supplier_type'] == 4){
//            $supplier_type_name = '保险供应商';
//        }elseif ($sup_data['supplier_type'] == 5){
//            $supplier_type_name = '国内物流';
//        }
        $supplier_type_name = IndexController::supplierTypeNameCommon($sup_data['supplier_type']);


        // 获取当前用户对应部门所设置的审批流设置
//        $flow = self::flowStting(2, $department_id);
        $flow = ApproveSettingController::flowSttingBySort(1, 0);
        if (!$flow) {
            return '当前用户所在部门未设置审批流程，无法提交审批';
        }


        $spf_no = 'SPFNO' . IndexController::getRandomNum(4).strtotime(date('H:i:s', time()));

        $data_approve = [
            'status' => 0, // 审批状态 待审批
            'spf_no' => $spf_no, // 审批流编号
            'service_type' => $sup_data['service_type'], // 服务类型
            'service_type_name' => $sup_data['service_type_name'], // 服务类型名称
            'supplier_id' => $sup_data['supplier_id'], // 供应商id
            'supplier_type' => $sup_data['supplier_type'], //  供应商类型： 1 车辆供应商 2 上牌供应商 3 国际货运代理 4 保险供应商 5 国内物流
            'supplier_type_name' => $supplier_type_name, //  供应商类型： 1 车辆供应商 2 上牌供应商 3 国际货运代理 4 保险供应商 5 国内物流
            'supplier_name' => $sup_data['supplier_name'], //  供应商名称
            'admin_id' => $adminId->id, // 创建人id
            'admin_name' => $adminId->nickname, // 创建人名称
            'created_at' => dateTime(), //
            'approve_flow' => json_encode($flow), // 当前采购合同的审批流流程
            'initiator_admin_name' => $adminId->nickname, // 审批发起人名称

        ];
        \support\Db::beginTransaction();
        try {
            // 创建供应商审批
            $add_SupplierEa_id =  WaSupplierExamineApprove::create($data_approve); // 创建的审批id
            if (!$add_SupplierEa_id) {
                return '创建供应商审批失败';
            }







            $approve_log_data = [
                'spf_no' => $spf_no, // 销售单审批编号
                'check_id' => intval($add_SupplierEa_id), // 审核id
//                'check_on' => $sales_approve->sale_no, // 审核编号
                'admin_ids' => json_encode($flow[0]->approve_flow), //
                'created_at' => dateTime(),
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'status' => 0, // 审核状态 0 待审核 1审批通过 2 审批驳回  3作废 4  删除
                'refuse_reason' => '',
                'initiator_admin_name' => $adminId->nickname, // 审批发起人
//                'describe' => '待' . $department->name . '审核'
            ];



            $approve_log_data_id = WaSupplierExamineApproveFlow::create($approve_log_data);
            if (!$approve_log_data_id) {
                return '创建车辆供应商日志失败';

            }



            \support\Db::commit();
            return  'true';

        } catch (\Throwable $exception) {
            IndexController::logError('commonCreateApprove', $sup_data, $adminId, $exception);
            \support\Db::rollBack();
            return '创建车辆供应商失败';
        }


    }



    /**
     * 定义供应商类型
     * @param Request $request
     * @return \string[][]
     */
    public static function supplierTypeList(Request $request){
        $res = [
            [
                'name' => '车辆供应商',
                'value' => 1,
                'code' => 'gys001',
            ],
            [
                'name' => '上牌应商',
                'value' => 2,
                'code' => 'gys002',
            ],
            [
                'name' => '保险公司',
                'value' => 3,
                'code' => 'gys003',
            ],
            [
                'name' => '国内物流',
                'value' => 4,
                'code' => 'gys004',
            ],
            [
                'name' => '国际货运代理',
                'value' => 5,
                'code' => 'gys005',
            ]
        ];
        return IndexController::successed(json_encode($res), '供应商类型列表');
    }




}